import sys
from UI.Print import Ui_Print

from Class.Area import MyArea
import fitz


class Reader(QDialog, Ui_Print):
    def __init__(self, parent=None):
        # 继承主窗口类
        super().__init__(parent)
        self.setupUi(self)
        self.current_page = 0
        # 获取屏幕对象
        # self.screen = QDesktopWidget().screenGeometry()
        self.size = (1, 1)  # 存储pdf页面大小
        self.area = MyArea(self)
        self.area.init(self)
        self.verticalLayout.addWidget(self.area)
        self.btnbig.clicked.connect(self.zoom_big)
        self.btnsmall.clicked.connect(self.zoom_small)
        self.btnpageback.clicked.connect(self.switch_pageback)
        self.btnpageforward.clicked.connect(self.switch_pageforward)
        self.btnprint.clicked.connect(self.showPrint)
        self.images = []

    def read_book(self, fname):
        """打开pdf文件"""
        # 打开pdf文件，doc为Document对象
        self.doc = fitz.open(fname)
        title = fname.split('/' or '\\')[-1].replace('.pdf', '')
        self.get_images()
        # 读取当前页
        self.set_page()

    def get_images(self):
        """将当前文件转为image列表"""
        self.images.clear()
        for i in range(self.doc.pageCount):
            page = self.doc.load_page(i)
            self.images.append(render_pdf_page1(page, size=(2.6, 2.6)))

    def switch_pageforward(self):
        if self.current_page < self.doc.pageCount - 1:
            self.current_page += 1
        self.set_page()

    def switch_pageback(self):
        if self.current_page > 0:
            self.current_page -= 1
        self.set_page()

    def set_page(self):
        """加载当前页"""
        page = self.doc.load_page(self.current_page)
        p = render_pdf_page(page, size=self.size)
        self.img = render_pdf_page1(page, size=(2.6, 2.6))
        # 在标签上显示图片
        label = QLabel()  # 括号里加上self就会有个错误警告，估计因为对象销毁问题
        # 在标签上设置图片
        label.setPixmap(QPixmap(p))
        self.area.setWidget(label)
        self.lblPageNo.setText(str(self.current_page +1) + "/" + str(self.doc.pageCount))

    def zoom_big(self):
        a, b = self.size
        a += 0.4
        b += 0.4
        self.size = (a, b)
        self.set_page()

    def zoom_small(self):
        a, b = self.size
        if a > 0:
            if a >= 1:
                a -= 0.4
                b -= 0.4
            self.size = (a, b)
            self.set_page()

    def get_file(self):
        # 打开单个文件
        fname, _ = QFileDialog.getOpenFileName(self, 'Open files', './', '(*.pdf)')
        return fname

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.doc.close()
        pass

    def showPrint(self):
        # 实例化打印图像对象
        printer = QPrinter()
        printer.setOrientation(QPrinter.Landscape)
        # 打印窗口弹出
        printdialog = QPrintDialog(printer)
        # 绘制
        if printdialog.exec():
            # 调用绘图
            painter = QPainter(printer)
            # 实例化视图窗口
            rect = painter.viewport()
            # 获取图片的尺寸
            size = self.img.size()
            # Qt.KeepAspectRatio  保持纵横比
            size.scale(rect.size(), Qt.KeepAspectRatio)
            # 设置窗口的大小为图片的磁村，并在窗口内绘制
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
            painter.setWindow(self.img.rect())
            painter.begin(self)  # 必须要有begin、end,否则报错QPaintDevice: Cannot destroy paint device that is being painted
            for img in self.images:
                painter.drawImage(0, 0, img)
            painter.end()


def render_pdf_page(page_data, *, size=(1, 1)):
    """将页面对象转换为可显示的pixmap对象"""
    # 图像缩放比例
    a, b = size
    zoom_matrix = fitz.Matrix(a, b)

    # 获取封面对应的 Pixmap 对象
    # alpha 设置背景为白色
    pagePixmap = page_data.get_pixmap(
        matrix=zoom_matrix,
        alpha=False)
    # 获取 image 格式
    imageFormat = QtGui.QImage.Format_RGB888
    # 生成 QImage 对象
    pageQImage = QtGui.QImage(
        pagePixmap.samples,
        pagePixmap.width,
        pagePixmap.height,
        pagePixmap.stride,
        imageFormat)

    # 生成 pixmap 对象
    pixmap = QtGui.QPixmap()
    pixmap.convertFromImage(pageQImage)
    return pixmap


def render_pdf_page1(page_data, *, size=(1, 1)):
    """将页面对象转换为可显示的pixmap对象"""
    # 图像缩放比例
    a, b = size
    zoom_matrix = fitz.Matrix(a, b)

    # 获取封面对应的 Pixmap 对象
    # alpha 设置背景为白色
    pagePixmap = page_data.get_pixmap(
        matrix=zoom_matrix,
        alpha=False)
    # 获取 image 格式
    imageFormat = QtGui.QImage.Format_RGB888
    # 生成 QImage 对象
    pageQImage = QtGui.QImage(
        pagePixmap.samples,
        pagePixmap.width,
        pagePixmap.height,
        pagePixmap.stride,
        imageFormat)
    return pageQImage


import os

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # <editor-fold desc="调用PYQT5自带的翻译文件">
    translator = QTranslator(app)
    if translator.load("qt_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
        app.installTranslator(translator)
    # </editor-fold>
    reader = Reader()
    reader.setAttribute(Qt.WA_DeleteOnClose)
    fname = reader.get_file()
    if fname != "":
        reader.read_book(fname)
        reader.exec()
    sys.exit(0)
